package com.securities.stock.utils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

	/**
	 * 生成随机数字验证码 长度可变
	 * @param length
	 * @return
	 */
	public static String randomVoidCode(int length){
		StringBuilder str=new StringBuilder();
		Random rm=new Random();
		for(int i=0;i<length;i++){
			str.append(rm.nextInt(10));
		}
		return str==null?null:str.toString();
	}

	/**
	 * 获取随机字符串 UUID  自带前缀
	 * @return
	 */
	public static String getPrefixRandomUUID(String strPrefix){
		return (strPrefix+getRandomUUID()).substring(0,35);
	}

	/**
	 * 获取随机字符串 UUID
	 * @return
	 */
	public static String getRandomUUID(){
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	public static String urlDecode(String str) throws UnsupportedEncodingException {
		if (str == null) {
			return null;
		}
		if (str.length() % 3 != 0) {
			return null;
		}
		byte[] arr = new byte[str.length() / 3];
		for (int i = 0; i <= str.length() - 3; i += 3) {
			//截取%后两位
			String temp = null;
			if (i == str.length() - 3) {
				temp = str.substring(i + 1);
			} else {
				temp = str.substring(i + 1, i + 3);
			}
			System.out.println(temp);
			//转换成自字节
			arr[i / 3] = (byte) Integer.parseInt(temp, 16);
		}
		System.out.println(Arrays.toString(arr));    //[-28, -72, -83, -27, -101, -67]
		//解码
		return new String(arr, 0, arr.length, "UTF-8");
	}


	static final Pattern reUnicode = Pattern.compile("\\\\u([0-9a-zA-Z]{4})");

	public static String decode(String s) {
		Matcher m = reUnicode.matcher(s);
		StringBuffer sb = new StringBuffer(s.length());
		while (m.find()) {
			m.appendReplacement(sb,
					Character.toString((char) Integer.parseInt(m.group(1), 16)));
		}
		m.appendTail(sb);
		return sb.toString();
	}
	
	
	 /**
     * 将数字转化为指定长度的字符串 不足位数数字前用0补足
     * 超出length将直接返回
     */
    public static String changeNumToStr(Object targetNum, int length) {
        String target = String.valueOf(targetNum);
        StringBuilder str = new StringBuilder();
        int num = length - target.length();
        if (num < 1) {
            return target;
        }
        for (int i = 0; i < num; i++) {
            str.append(0);
        }
        return str.toString() + target;
    }
}
